package com.template.templateuser.auth.serviceauth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.template.templatecommon.domain.Result;
import com.template.templateuser.auth.serviceauth.customImpl.MyRedisTokenStore;
import com.template.templateuser.common.constants.UserConstants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.security.Principal;
import java.util.Collection;
import java.util.Map;

/**
 * @author fengpt
 * @createTime 2019年11月29日 17:45:00
 */
@RequestMapping("/users")
@Controller
public class UserLoginController {
    Logger logger = LoggerFactory.getLogger(UserLoginController.class);


    @Autowired
    MyRedisTokenStore myRedisTokenStore;
    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public void getVerifyCode(HttpServletResponse response, HttpSession session)throws Exception{
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        OutputStream out = response.getOutputStream();
        captcha.write(out);
        response.setContentType(String.valueOf(MediaType.IMAGE_PNG));
        session.setAttribute(UserConstants.VERIFYCODE_SESSION_PRIFIXX,captcha.getCode());
        out.flush();
        out.close();
    }
    @RequestMapping(value = "/current", method = RequestMethod.GET)
    @ResponseBody
    public Principal getUser(Map map,Principal principal,Authentication  authentication) {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>");
        logger.info(principal.toString());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>");
        return principal;
    }


/*    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey("username")) {
            Object principal = map.get("username");
            Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);
            if (this.userDetailsService != null) {
                UserDetails user = this.userDetailsService.loadUserByUsername((String)map.get("user_name"));
                authorities = user.getAuthorities();
                principal = user;
            }
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        } else {
            return null;
        }
    }*/



    //
    @GetMapping(value = "/user/logout")
    @ResponseBody
    public String logout(HttpServletRequest request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null && (authentication instanceof OAuth2Authentication)) {
            String authorization = request.getHeader("Authorization");
            if(StringUtils.isNotBlank(authorization))
                myRedisTokenStore.removeAccessToken(authorization.replaceAll("Bearer ", ""));
        }
        return "success";
    }
}
